package Base;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import java.io.*;

public class FileOperation {

    // 通过字符串类型读取文件
    public static String read(String path){
        File file = new File(path);
        byte[] bytes = new byte[1024];

        try {
            new FileInputStream(file).read(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return new String(bytes);
    }

    // 通过字符串类型写入文件
    public static void write(String path, String data){
        File file = new File(path);
        if(!file.exists()){
            System.out.println("文件不存在,正在创建文件并继续");
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        try {
            new FileOutputStream(file).write(data.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 通过json读取文件
    public static JSONObject readJson(String path){
        String data = read(path);
        return JSONObject.parseObject(data);
    }

    // 通过json写入文件
    public static void writeJson(String path, JSONObject data){
        write(path, data.toJSONString(JSONWriter.Feature.PrettyFormat));
    }
}
